package cn.wolfcode.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.domain.NoticeItem;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        DateTime date = DateUtil.date(System.currentTimeMillis());
        notice.setCreatTime(date);
        notice.setStatus(false);
        Employee user = UserContext.getCurrentUser();
        notice.setCreator(user);
        NoticeItem item = new NoticeItem();
        notice.setItem(item);
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit

        for (Notice notice : notices) {
            Long id = noticeMapper.checkId(UserContext.getCurrentUser().getId(), notice.getId());

            if(id!=null){
                //如果id他这个id不等于空的话就证明他那个已经读过了所以放进去
                notice.setReadStatus(true);

            }
            else {
                //
                notice.setReadStatus(false);
                return new PageInfo<>(notices);
            }
        }

        return new PageInfo<Notice>(notices);
    }

    @Override
    public Notice selectById(Long id) {
        return noticeMapper.selectById(id);
    }

    @Override
    public Long checkId(Long id,Long nid) {
        return noticeMapper.checkId(id,nid);
    }

    @Override
    public void insertRelation(Long id, Long id1) {
        noticeMapper.insertRelation(id,id1);
    }

    @Override
    public void updateStatus(Long id,boolean status) {
        noticeMapper.updateStatus(id,status);
    }

    @Override
    public boolean selectByStatus(Long id) {
        return noticeMapper.selectByStatus(id);
    }
}
